package com.waves.message.service.impl;

import cn.hutool.core.lang.Assert;
import com.waves.core.utils.JsonUtils;
import com.waves.message.dto.MessageRecordInsertDTO;
import com.waves.message.model.SendMessageModel;
import com.waves.message.service.MessageRecordService;
import com.waves.message.service.MessageService;
import com.waves.message.service.SendMessageService;
import com.waves.message.vo.MessageTemplateVO;
import jodd.util.StringTemplateParser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Eden
 * @date 2025/01/01 15:57
 **/
@Service
@RequiredArgsConstructor
public class SendMessageServiceImpl implements SendMessageService {

    private final MessageService messageService;
    private final MessageRecordService messageRecordService;


    @Override
    @Transactional
    public boolean sendMessage(SendMessageModel sendMessageModel) {
        //入参校验
        List<Long> receptionUserIds = sendMessageModel.getReceptionUserIds();
        Assert.notEmpty(receptionUserIds, "接收人员不能为空");
        String messageTemplateCode = sendMessageModel.getMessageTemplateCode();
        Assert.notBlank(messageTemplateCode, "消息模版编码不能为空");
        MessageTemplateVO messageByCode = messageService.getMessageByCode(messageTemplateCode);
        Assert.notNull(messageByCode, "消息模版不存在");
        //新增记录
        MessageRecordInsertDTO messageRecordInsertDTO = new MessageRecordInsertDTO();
        BeanUtils.copyProperties(sendMessageModel, messageRecordInsertDTO);
        messageRecordInsertDTO.setParameter(
                JsonUtils.toJsonString(sendMessageModel.getMessageContextMap()));
        messageRecordInsertDTO.setCreatedBy(sendMessageModel.getSenderId());
        //消息模版拼接
        String messageContext = StringTemplateParser.ofMap(sendMessageModel.getMessageContextMap())
                                                    .apply(messageByCode.getTemplate());
        messageRecordInsertDTO.setMessageContext(messageContext);
        messageRecordInsertDTO.setTitle(messageByCode.getTitle());
        messageRecordInsertDTO.setTemplateCode(messageByCode.getCode());
        messageRecordInsertDTO.setName(messageByCode.getName());
        for (Long receptionUserId : receptionUserIds) {
            messageRecordInsertDTO.setReceptionUserId(receptionUserId);
            messageRecordService.insert(messageRecordInsertDTO);
        }
        return true;
    }
}
